package com.hxtec.polaris.commons.exception;

import javax.servlet.http.HttpServletRequest;

import com.hxtec.polaris.commons.api.vo.Result;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Author yonyong
 * @Description //TODO
 * @Date 2019/11/11 14:27
 * @Param
 * @return
 **/
@ControllerAdvice
public class MyExceptionHandler {

    private final static Logger logger = LoggerFactory.getLogger(MyExceptionHandler.class);

    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    public Object handle(Exception e, HttpServletRequest request) {
        if (e instanceof MyException) {
            MyException myException = (MyException) e;
            if (StringUtils.isNotBlank(myException.getLogMsg())){
                Result result = (Result) myException.getResult();
                logger.error(myException.getLogMsg()
                        + "\n" + result.getCode()+result.getMessage()
                        + "\n" + myException.getMessage()
                        + "\n" );
            }
            return myException.getResult();
        }else {
            // 直接将异常对象传入日志接口，保存异常信息到日志文件中
            logger.error("error: {}"+"\n", e.getMessage(), e);
            return Result.error("服务器异常");
        }
    }
}
